package com.example.suhui_test.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.example.suhui_test.IUserService;
import com.example.suhui_test.User;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

// 添加Trace导入
import android.os.Trace;

/**
 * 用户管理服务实现
 * 提供用户管理功能的AIDL服务端实现
 */
public class UserService extends Service {
    private static final String TAG = "UserService";    
    
    // 线程安全的用户列表
    private final CopyOnWriteArrayList<User> userList = new CopyOnWriteArrayList<>();

    @Override
    public void onCreate() {
        super.onCreate();
        // 修改Trace标记，明确表示服务生命周期事件
        Trace.beginSection("Service_lifecycle_onCreate");
        Log.d(TAG, "User service created, process ID: " + android.os.Process.myPid());
        Log.d(TAG, "Service creation stack trace:", new Throwable("Service creation trace"));
        
        // 初始化一些测试数据
        initTestData();
        // 结束Trace标记
        Trace.endSection();
    }
    
    /**
     * 初始化测试数据
     */
    private void initTestData() {
        // 修改Trace标记，明确表示服务内部方法调用
        Trace.beginSection("Service_internal_initTestData");
        Log.d(TAG, "Starting to initialize test data");
        userList.add(new User(1, "Zhang San", "zhangsan@example.com"));
        userList.add(new User(2, "Li Si", "lisi@example.com"));
        userList.add(new User(3, "Wang Wu", "wangwu@example.com"));
        Log.d(TAG, "Test data initialization completed, user count: " + userList.size());
        Log.d(TAG, "Initialized user list: " + userList);
        // 结束Trace标记
        Trace.endSection();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // 修改Trace标记，明确表示服务处理的绑定请求
        Trace.beginSection("Service_handled_onBind");
        Log.d(TAG, "Service bind request, Intent: " + intent);
        Log.d(TAG, "Binding component: " + intent.getComponent());
        Log.d(TAG, "Binding Action: " + intent.getAction());
        Log.d(TAG, "Service binding stack trace:", new Throwable("Service binding trace"));
        // 结束Trace标记
        Trace.endSection();
        return userServiceStub;
    }

    @Override
    public boolean onUnbind(Intent intent) {
        // 修改Trace标记，明确表示服务处理的解绑请求
        Trace.beginSection("Service_handled_onUnbind");
        Log.d(TAG, "Service unbind request, Intent: " + intent);
        boolean result = super.onUnbind(intent);
        Log.d(TAG, "Service unbind completed, result: " + result);
        // 结束Trace标记
        Trace.endSection();
        return result;
    }

    @Override
    public void onDestroy() {
        // 修改Trace标记，明确表示服务生命周期事件
        Trace.beginSection("Service_lifecycle_onDestroy");
        Log.d(TAG, "User service destruction started");
        Log.d(TAG, "Service destruction stack trace:", new Throwable("Service destruction trace"));
        super.onDestroy();
        Log.d(TAG, "User service destruction completed");
        // 结束Trace标记
        Trace.endSection();
    }

    /**
     * AIDL接口实现
     */
    private final IUserService.Stub userServiceStub = new IUserService.Stub() {
        @Override
        public List<User> getAllUsers() throws RemoteException {
            // 修改Trace标记，明确表示服务处理的获取所有用户请求
            Trace.beginSection("Service_handled_getAllUsers");
            Log.d(TAG, "Get all users request, current thread: " + Thread.currentThread().getName());
            Log.d(TAG, "Getting all users, count: " + userList.size());
            List<User> result = new ArrayList<>(userList);
            Log.d(TAG, "Get all users completed, returning user list: " + result);
            // 结束Trace标记
            Trace.endSection();
            return result;
        }

        @Override
        public User getUserById(int id) throws RemoteException {
            // 修改Trace标记，明确表示服务处理的按ID获取用户请求
            Trace.beginSection("Service_handled_getUserById");
            Log.d(TAG, "Get user by ID request, ID: " + id);
            for (User user : userList) {
                if (user.getId() == id) {
                    Log.d(TAG, "Found user: " + user);
                    // 结束Trace标记
                    Trace.endSection();
                    return user;
                }
            }
            Log.d(TAG, "User with ID " + id + " not found");
            // 结束Trace标记
            Trace.endSection();
            return null;
        }

        @Override
        public void addUser(User user) throws RemoteException {
            // 修改Trace标记，明确表示服务处理的添加用户请求
            Trace.beginSection("Service_handled_addUser");
            Log.d(TAG, "Add user request, user info: " + user);
            if (user != null) {
                Log.d(TAG, "Adding user: " + user.getName());
                userList.add(user);
                Log.d(TAG, "User added successfully, current user count: " + userList.size());
            } else {
                Log.w(TAG, "Attempting to add null user");
                // 打印堆栈跟踪用于调试
                Log.d(TAG, "堆栈跟踪:", new Throwable("空用户添加尝试"));
            }
            // 结束Trace标记
            Trace.endSection();
        }

        @Override
        public void deleteUser(int id) throws RemoteException {
            // 修改Trace标记，明确表示服务处理的删除用户请求
            Trace.beginSection("Service_handled_deleteUser");
            Log.d(TAG, "Delete user request, ID: " + id);
            boolean deleted = false;
            for (int i = 0; i < userList.size(); i++) {
                if (userList.get(i).getId() == id) {
                    User deletedUser = userList.remove(i);
                    Log.d(TAG, "User deleted successfully: " + deletedUser);
                    deleted = true;
                    break;
                }
            }
            if (!deleted) {
                Log.d(TAG, "User with ID " + id + " not found for deletion");
            }
            Log.d(TAG, "Delete user operation completed, current user count: " + userList.size());
            // 结束Trace标记
            Trace.endSection();
        }

        @Override
        public int getUserCount() throws RemoteException {
            // 修改Trace标记，明确表示服务处理的获取用户数量请求
            Trace.beginSection("Service_handled_getUserCount");
            Log.d(TAG, "Get user count request");
            int count = userList.size();
            Log.d(TAG, "Get user count completed, count: " + count);
            // 结束Trace标记
            Trace.endSection();
            return count;
        }
    };
}